package com.cmy.framework_widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView


/**
 * @name:
 *  TitleView
 * @package:
 *  com.cmy.framework_widget
 * @date:
 *  2023/4/2315:43
 * @author
 *    cmy
 * @description
 *   自定义标题（未完成）
 */
class TitleView :ViewGroup {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?,defStyleAttr:Int = 0):super(context, attrs,defStyleAttr)

    private lateinit var mLeftView: View
    private lateinit var mTitleView: TextView
    private lateinit var mRightView: View

    init {
        init()
    }

    @SuppressLint("SetTextI18n")
    private fun init() {
        // 添加子View
        mLeftView = ImageView(context)
//        (mLeftView as ImageView).setImageResource(R.drawable.ic_back)
        addView(mLeftView)
        mTitleView = TextView(context)
        mTitleView.text = "Title"
        addView(mTitleView)
        mRightView = ImageView(context)
//        (mRightView as ImageView).setImageResource(R.drawable.ic_menu)
        addView(mRightView)
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        // 测量子View的大小
        measureChild(mLeftView, widthMeasureSpec, heightMeasureSpec)
        measureChild(mTitleView, widthMeasureSpec, heightMeasureSpec)
        measureChild(mRightView, widthMeasureSpec, heightMeasureSpec)
        // 设置自身大小
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)
        setMeasuredDimension(width, height)
    }
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        // 布局子View
        var left = 0
        var top = 0
        var right = mLeftView.measuredWidth
        var bottom = mLeftView.measuredHeight
        mLeftView.layout(left, top, right, bottom)
        left = (width - mTitleView.measuredWidth) / 2
        top = 0
        right = left + mTitleView.measuredWidth
        bottom = mTitleView.measuredHeight
        mTitleView.layout(left, top, right, bottom)
        left = width - mRightView.measuredWidth
        top = 0
        right = width
        bottom = mRightView.measuredHeight
        mRightView.layout(left, top, right, bottom)
    }


    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas?) {
        // 绘制背景和分割线
        super.onDraw(canvas)
        val paint = Paint()
        paint.color = Color.GRAY
        canvas?.drawLine(0F, (height - 1).toFloat(), width.toFloat(), (height - 1).toFloat(), paint)
    }


}